package com.sduept.nwld.dataserver.controller.equipment.assessment;

import com.alibaba.fastjson.JSONObject;
import com.sduept.bigdata.equipment.assessment.dto.InspectOtherTreeTableDTO;
import com.sduept.bigdata.equipment.assessment.enums.InspectionType;
import com.sduept.bigdata.equipment.assessment.enums.SubStationTypeEnum;
import com.sduept.bigdata.equipment.assessment.exception.ParameterException;
import com.sduept.bigdata.equipment.assessment.model.inspection.InspectionExpert;
import com.sduept.bigdata.equipment.assessment.model.inspection.InspectionPlan;
import com.sduept.bigdata.equipment.assessment.model.inspection.InspectionStation;
import com.sduept.bigdata.equipment.assessment.service.*;
import com.sduept.bigdata.web.jsf.controller.AbstractController;
import com.sduept.cim.ledger.enums.ManagementUnitEnum;
import com.sduept.cim.ledger.excetpion.ManagementUnitException;
import com.sduept.cim.ledger.manager.SubstationLedgerManager;
import com.sduept.cim.ledger.model.ManagementUnitDict;
import com.sduept.cim.ledger.services.ManagementUnitService;
import com.sduept.generator.ObjectId;
import com.sduept.permission.entity.PersonnelEntityBean;
import com.sduept.permission.manager.DepartManager;
import com.sduept.utils.PingYinUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.primefaces.PrimeFaces;
import org.springframework.beans.factory.annotation.Autowired;

import javax.annotation.PostConstruct;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.view.ViewScoped;
import javax.inject.Named;
import java.util.*;
/**
 * 新建或编辑互查计划弹窗控制器
 * @author pengz
 *
 */
@Slf4j
@Named
@ViewScoped
public class AddInspectOtherPlanController extends AbstractController{

	private static final long serialVersionUID = -3493794679432094666L;
	@Autowired
	private ManagementUnitService unitService;
	@Autowired
	private DepartManager orgService;
	@Autowired
	private InspectionExpertService expertService;
	@Autowired
	private InspectionItemService itemService;
	@Autowired
	private InspectionPlanService planService;
	@Autowired
	private StandardInspectService standService;
	@Autowired
	private InspectionStationService stationService;

	@Autowired
	private SubstationLedgerManager stationLedgerM;
	/**
	 * 传递的参数：计划id
	 */
	private String planId;
	/**
	 * 检修范围（被检分子公司）名称+运维单位（被检单位）名称-人员
	 */
	private Map<String,List<PersonnelEntityBean>> unitNameToPersonnels;
	/**
	 * key:运维单位+人员名称
	 * value:人员
	 */
	private Map<String,PersonnelEntityBean> personnelMap;
	/**
	 * key:检修范围名称
	 * value：该检修范围下的人员
	 */
	private Map<String,List<PersonnelEntityBean>> scopeNameToPersonnels;
	/**
	 * 目标计划
	 */
	private InspectionPlan targetPlan;
	/**
	 * 页面展示信息列表
	 */
	private List<InspectOtherTreeTableDTO> inspectOtherModels;
	/**
	 * key:派出专家分子公司
	 * value:map -> key:组名称   value:出现次数
	 */
	private Map<String,Map<Integer,Integer>> inspectionScopeNameToGroup;
	private Map<String,List<ManagementUnitDict>> scopeNameToUnits;
	private List<InspectionExpert> expertAll;
	
	private List<InspectOtherTreeTableDTO> selectedModels;
	/**
	 * 记录已选择的专家，因为每个专家只能 选择一次
	 */
	private List<String> selectedExperts;	
	/**
	 * 派出专家分子公司对应的被检单位数
	 * key:派出分子公司名称
	 */
	private Map<String,Integer> inspectionScopeToAcceptUnitNum;
	/**
	 * 被检分子公司对应的被检单位数
	 * key:派出专家分子公司名称+被检分子公司名称
	 */
	private Map<String,Integer> acceptScopeToAcceptUnitNum;
	{
		unitNameToPersonnels = new HashMap<String, List<PersonnelEntityBean>>();
		personnelMap = new HashMap<String, PersonnelEntityBean>();
		inspectOtherModels = new ArrayList<InspectOtherTreeTableDTO>();
		scopeNameToPersonnels = new HashMap<String, List<PersonnelEntityBean>>();
		inspectionScopeNameToGroup = new HashMap<String, Map<Integer,Integer>>();
		scopeNameToUnits = new HashMap<String, List<ManagementUnitDict>>();
		selectedModels = new ArrayList<InspectOtherTreeTableDTO>();
		selectedExperts = new ArrayList<String>();
		inspectionScopeToAcceptUnitNum = new HashMap<String, Integer>();
		acceptScopeToAcceptUnitNum = new HashMap<String, Integer>();
	}
	@PostConstruct
	public void init() {
		initParamter();
		initTargetPlan();
		initData();
	}
	/**
	 * 初始化所需数据
	 */
	private void initData() {
		//加载所有的专家
		expertAll = expertService.findAll();
	}
	/**
	 * 初始化传入的参数信息
	 */
	private void initParamter() {
		planId = getParameter("id");
	}
	/**
	 * 初始化targetPlan
	 */
	private void initTargetPlan() {
		if(StringUtils.isNotEmpty(planId)) {
			targetPlan = planService.findById(planId);
			try {
				Set<InspectionStation> currentInstations = stationService.findByInspectionPlan(planId);
				initInspectOtherModels(currentInstations);
				sortModelList(inspectOtherModels);
			} catch (ParameterException e) {
				e.printStackTrace();
			}
		}else {
			targetPlan = new InspectionPlan();
			//评价类型：互查
			targetPlan.setInspectionType(InspectionType.INSPECTIONOTHER);
			//创建人：当前用户
			targetPlan.setCreator(getCurrentUser().getName());
		}
		
	}
	/**
	 * 初始化inspectionOtherModels
	 * @param currentInstations
	 */
	private void initInspectOtherModels(Set<InspectionStation> currentInstations) {
		inspectionScopeNameToGroup.clear();
		inspectOtherModels.clear();
		for(InspectionStation instation : currentInstations) {
			//1.初始化inspectionScopeToAcceptUnitNum
			if(!inspectionScopeToAcceptUnitNum.containsKey(instation.getInspectionScope())) {
				inspectionScopeToAcceptUnitNum.put(instation.getInspectionScope(), 0);
			}
			Integer num1 = inspectionScopeToAcceptUnitNum.get(instation.getInspectionScope());
			num1++;
			inspectionScopeToAcceptUnitNum.replace(instation.getInspectionScope(), num1);
			//2.初始化acceptScopeToAcceptUnitNum
			String key = instation.getInspectionScope()+"-"+instation.getAcceptScope();
			if(!acceptScopeToAcceptUnitNum.containsKey(key)) {
				acceptScopeToAcceptUnitNum.put(key, 0);
			}
			Integer num2 = acceptScopeToAcceptUnitNum.get(key);
			num2++;
			acceptScopeToAcceptUnitNum.replace(key, num2);
			//3.生成展示模型
			InspectOtherTreeTableDTO model = generateModelFromInspectionStation(instation);
			inspectOtherModels.add(model);
		}
	}
	/**
	 * 将InspectionStation -> InspectOtherTreeTableDTO
	 * @param inspectionStation
	 * @return
	 */
	private InspectOtherTreeTableDTO generateModelFromInspectionStation(InspectionStation inspectionStation) {
		InspectOtherTreeTableDTO model = new InspectOtherTreeTableDTO();
		model.setFormDB(true);
		model.setInspectionStationId(inspectionStation.getId());
		model.setInspectionScope(inspectionStation.getInspectionScope());
		model.setAcceptScope(inspectionStation.getAcceptScope());
		model.setAcceptUnit(inspectionStation.getAcceptUnit());
		model.setStationPersonnel(inspectionStation.getStationPersonnel());
		model.setStationPersonnelPhone(inspectionStation.getStationPersonnelPhone());
		model.setInspectionScopePersonnel(inspectionStation.getInspectionScopePersonnel());
		model.setInspectionScopePersonnelPhone(inspectionStation.getInspectionScopePersonnelPhone());
		model.setInspectionExpert(inspectionStation.getInspectionExpert());
		model.setOldInspectionExpert(inspectionStation.getInspectionExpert());
		if(StringUtils.isNotBlank(inspectionStation.getInspectionExpert())) {
			selectedExperts.add(inspectionStation.getInspectionExpert());
		}
		model.setInspectionExpertId(inspectionStation.getInspectionExpertId());
		model.setInspectionExpertPhone(inspectionStation.getInspectionExpertPhone());
		model.setInspectionUnit(inspectionStation.getInspectionUnit());
		model.setStartTime(inspectionStation.getStartTime());
		model.setEndTime(inspectionStation.getEndTime());
		model.setStationId(inspectionStation.getStationId());
		model.setStationName(inspectionStation.getStationName());
		if(inspectionStation.getStationType()!=null) {
			model.setStationType(inspectionStation.getStationType().name());
		}
		if(inspectionStation.getInspectionExpertGroup()!=0) {
			model.setInspectionExpertGroup(inspectionStation.getInspectionExpertGroup()+"");
			model.setOldInspectionExpertGroup(inspectionStation.getInspectionExpertGroup()+"");
			if(!inspectionScopeNameToGroup.containsKey(inspectionStation.getInspectionScope())) {
				Map<Integer,Integer> groups = new HashMap<Integer, Integer>();
				inspectionScopeNameToGroup.put(inspectionStation.getInspectionScope(), groups);
			}
			Map<Integer, Integer> groups = inspectionScopeNameToGroup.get(inspectionStation.getInspectionScope());
			if(groups.containsKey(inspectionStation.getInspectionExpertGroup())) {
				Integer count = groups.get(inspectionStation.getInspectionExpertGroup());
				count++;
				groups.replace(inspectionStation.getInspectionExpertGroup(), count);
			}else {
				groups.put(inspectionStation.getInspectionExpertGroup(), 1);
			}
		}else {
			model.setInspectionExpertGroup("");
		}
		return model;
	}
	/**
	 * 
	 * @param inspectionScope
	 * @return
	 */
	public int getAcceptUnitNumFromInspectionScope(String inspectionScope) {
		return inspectionScopeToAcceptUnitNum.get(inspectionScope);
	}
	/**
	 * 
	 * @param inspectionScope
	 * @param acceptScope
	 * @return
	 */
	public int getAcceptUnitNumFromAcceptScope(String inspectionScope,String acceptScope) {
		String key = inspectionScope+"-"+acceptScope;
		return acceptScopeToAcceptUnitNum.get(key);
	}
	/**
	 * 被检单位联系人响应autocomplete集合
	 * @param model
	 * @return
	 */
	public List<String> completeStationPersonnels(String query) {
		List<String> result = new ArrayList<String>();
		List<PersonnelEntityBean> personnels = new ArrayList<PersonnelEntityBean>();
		InspectOtherTreeTableDTO modelOnFocus = getModelOnFocus();
		if(StringUtils.isNotBlank(modelOnFocus.getAcceptUnit())) {
			String key = modelOnFocus.getAcceptScope()+"-"+modelOnFocus.getAcceptUnit();
			if(unitNameToPersonnels.containsKey(key)) {
				personnels = unitNameToPersonnels.get(key);
			}else {
				ManagementUnitDict unit = null;
				try {
					ManagementUnitDict scope = unitService.getManagementUnitByName(modelOnFocus.getAcceptScope());
					List<ManagementUnitDict> units = unitService.getManagementUnitByParent(scope.getId());
					for(ManagementUnitDict managementUnitDict : units) {
						if(managementUnitDict.getName().equals(modelOnFocus.getAcceptUnit())) {
							unit = managementUnitDict;
							break;
						}
					}
//					if(unit==null) {
//						unit = unitService.getManagementUnitByName(modelOnFocus.getAcceptUnit());
//					}
				} catch (ManagementUnitException e) {
					e.printStackTrace();
				}
				if(unit!=null) {
					personnels = orgService.findDeptPersonnels(unit.getId());
					unitNameToPersonnels.put(key, personnels);
					for(PersonnelEntityBean personnel : personnels) {
						personnelMap.put(modelOnFocus.getAcceptUnit()+"-"+personnel.getName(), personnel);
					}
				}
			}
		}
		if(StringUtils.isNotBlank(query)) {
			for(PersonnelEntityBean personnel : personnels) {
				if(PingYinUtil.getPingYinHeader(personnel.getName()).startsWith(query)) {
					result.add(personnel.getName());
				}
			}
		}else {
			for(PersonnelEntityBean personnel : personnels) {
				result.add(personnel.getName());
			}
			
		}
		return result;
	}
	/**
	 * 处理被检单位迎检人员选中事件
	 * @param event
	 */
	public void onStationPersonnelSelect(InspectOtherTreeTableDTO model) {
		if(StringUtils.isNotBlank(model.getStationPersonnel())) {
			String key = model.getAcceptUnit()+"-"+model.getStationPersonnel();
			if(personnelMap.containsKey(key)) {
				PersonnelEntityBean selectedPersonnel = personnelMap.get(key);
				model.setStationPersonnelPhone(selectedPersonnel.getTelephone());
			}
		}
	}
	/**
	 * 派出分子公司联系人响应autocomplete集合
	 * @param model
	 * @return
	 */
	public List<String> completeInspectionScopePersonnels(String query) {
		List<String> result = new ArrayList<String>();
		InspectOtherTreeTableDTO modelOnFocus = getModelOnFocus();
		if(StringUtils.isNotBlank(modelOnFocus.getInspectionScope())) {
			if(modelOnFocus.getInspectionScope().contains(",")) {
				String[] inspectionScopes = modelOnFocus.getInspectionScope().split(",");
				Map<String,List<PersonnelEntityBean>> scopeToPersonnelMap = new HashMap<String, List<PersonnelEntityBean>>();
				for(int i=0;i<inspectionScopes.length;i++) {
					scopeToPersonnelMap.put(inspectionScopes[i], generateScopeNameToPersonnels(inspectionScopes[i]));
				}
				//生成result
				if(StringUtils.isNotBlank(query)) {
					for(String scope : scopeToPersonnelMap.keySet()) {
						List<PersonnelEntityBean> personnels = scopeToPersonnelMap.get(scope);
						for(PersonnelEntityBean personnel : personnels) {
							if(PingYinUtil.getPingYinHeader(personnel.getName()).startsWith(query)) {
//								result.add(personnel.getName()+"("+scope+")");
								result.add(personnel.getName());
							}
						}
					}
				}else {
					for(String scope : scopeToPersonnelMap.keySet()) {
						List<PersonnelEntityBean> personnels = scopeToPersonnelMap.get(scope);
						for(PersonnelEntityBean personnel : personnels) {
//							result.add(personnel.getName()+"("+scope+")");
							result.add(personnel.getName());
						}
					}
				}
			}else {
				List<PersonnelEntityBean> personnels = generateScopeNameToPersonnels(modelOnFocus.getInspectionScope());
				//生成result
				if(StringUtils.isNotBlank(query)) {
					for(PersonnelEntityBean personnel : personnels) {
						if(PingYinUtil.getPingYinHeader(personnel.getName()).startsWith(query)) {
							result.add(personnel.getName());
						}
					}
				}else {
					for(PersonnelEntityBean personnel : personnels) {
						result.add(personnel.getName());
					}
				}
			}
			
		}
		return result;
	}
	private List<PersonnelEntityBean> generateScopeNameToPersonnels(String inspectionScope) {
		List<PersonnelEntityBean> personnels = new ArrayList<PersonnelEntityBean>();
		if(scopeNameToPersonnels.containsKey(inspectionScope)) {
			personnels = scopeNameToPersonnels.get(inspectionScope);
		}else {
			ManagementUnitDict unit = null;
			try {
				unit = unitService.getManagementUnitByName(inspectionScope);
				if(unit!=null) {
					personnels = orgService.recursiveFindDepartPersonnels(unit.getId());
					scopeNameToPersonnels.put(inspectionScope, personnels);
				}
				for(PersonnelEntityBean personnel : personnels) {
					if(!personnelMap.containsKey(inspectionScope+"-"+personnel.getName())) {
						personnelMap.put(inspectionScope+"-"+personnel.getName(), personnel);
					}
				}
			} catch (ManagementUnitException e) {
				e.printStackTrace();
			}
		}
		return personnels;
	}
	/**
	 * 派出分子公司联系人选中处理函数
	 * @param model
	 */
	public void onInspectionScopePersonnelSelect(InspectOtherTreeTableDTO model) {
		if(StringUtils.isNotBlank(model.getInspectionScopePersonnel())) {
//			String inspectionScopePersonnel = "";
//			String inspectionScope = "";
//			if(model.getInspectionScopePersonnel().contains("(")) {
//				String sp = model.getInspectionScopePersonnel();
//				String[] inspectionScopePersonnelArray = sp.split("\\(");
//				inspectionScopePersonnel = inspectionScopePersonnelArray[0];
//				int index = inspectionScopePersonnelArray[1].indexOf(")");
//				inspectionScope = inspectionScopePersonnelArray[1].substring(0,index);
//			}else {
//				inspectionScopePersonnel = model.getInspectionScopePersonnel();
//				inspectionScope = model.getInspectionScope();
//			}
			if(model.getInspectionScope().contains(",")) {
				String[] inspectionScopes = model.getInspectionScope().split(",");
				for(int i=0;i<inspectionScopes.length;i++) {
					String key = inspectionScopes[i]+"-"+model.getInspectionScopePersonnel();
					if(personnelMap.containsKey(key)) {
						PersonnelEntityBean selectedPersonnel = personnelMap.get(key);
						model.setInspectionScopePersonnelPhone(selectedPersonnel.getTelephone());
						return;
					}
				}
			}else {
				String key = model.getInspectionScope()+"-"+model.getInspectionScopePersonnel();
				if(personnelMap.containsKey(key)) {
					PersonnelEntityBean selectedPersonnel = personnelMap.get(key);
					model.setInspectionScopePersonnelPhone(selectedPersonnel.getTelephone());
				}
			}
			
		}
	}
	/**
	 * 专家分组处理函数
	 * @param model
	 */
	public void onInspectionExpertGroupBlur(InspectOtherTreeTableDTO model) {
		long start = System.currentTimeMillis();
		if(StringUtils.isNotBlank(model.getInspectionExpertGroup())) {
			if(StringUtils.isNumeric(model.getInspectionExpertGroup())) {
				boolean add = false;
				if(StringUtils.isBlank(model.getOldInspectionExpertGroup())) {
					add = true;
				}else {
					if(!model.getInspectionExpertGroup().equals(model.getOldInspectionExpertGroup())) {
						add = true;
					}
				}
				if(add) {
					//添加
					int newGroup = Integer.parseInt(model.getInspectionExpertGroup());
					if(!inspectionScopeNameToGroup.containsKey(model.getInspectionScope())) {
						Map<Integer,Integer> groups = new HashMap<Integer, Integer>();
						inspectionScopeNameToGroup.put(model.getInspectionScope(), groups);
					}
					Map<Integer, Integer> groups = inspectionScopeNameToGroup.get(model.getInspectionScope());
					if(groups.containsKey(newGroup)) {
						Integer count = groups.get(newGroup);
						if(count==2) {
							if(StringUtils.isNotBlank(model.getOldInspectionExpertGroup())) {
								model.setInspectionExpertGroup(model.getOldInspectionExpertGroup());
							}else {
								model.setInspectionExpertGroup("");
							}
							addErrorMessage("["+newGroup+"]组已满，请选择其他组！");
						}else {//count==1或0   //分组成功
							count++;
							groups.replace(newGroup, count);
							if(StringUtils.isNotBlank(model.getOldInspectionExpertGroup())) {
								int oldGroup = Integer.parseInt(model.getOldInspectionExpertGroup());
								if(groups.containsKey(oldGroup)) {
									Integer count1 = groups.get(oldGroup);
									count1--;
									groups.replace(oldGroup, count1);
								}
							}
							model.setOldInspectionExpertGroup(model.getInspectionExpertGroup());
						}
					}else {//分组成功
						groups.put(newGroup, 1);
						if(StringUtils.isNotBlank(model.getOldInspectionExpertGroup())) {
							int oldGroup = Integer.parseInt(model.getOldInspectionExpertGroup());
							if(groups.containsKey(oldGroup)) {
								Integer count1 = groups.get(oldGroup);
								count1--;
								groups.replace(oldGroup, count1);
							}
						}
						model.setOldInspectionExpertGroup(model.getInspectionExpertGroup());
					}					
				}
				
			}else {
				model.setInspectionExpertGroup("");
				addErrorMessage("请输入数字！");
			}
			long end = System.currentTimeMillis();
			log.info("分组用时："+(end-start));
		}
	}
	/**
	 * 派出专家供电局响应autocomplete集合
	 * @param model
	 * @return
	 */
	public List<String> completeInspectionUnits(String query) {
		List<String> result = new ArrayList<String>();
		List<ManagementUnitDict> managements = new ArrayList<ManagementUnitDict>();
		InspectOtherTreeTableDTO modelOnFocus = getModelOnFocus();
		if(StringUtils.isNotBlank(modelOnFocus.getInspectionScope())) {
			if(scopeNameToUnits.containsKey(modelOnFocus.getInspectionScope())) {
				managements = scopeNameToUnits.get(modelOnFocus.getInspectionScope());
			}else {
				try {
					String[] inspectionStrs = modelOnFocus.getInspectionScope().split(",");
					for(String s : inspectionStrs) {
						ManagementUnitDict scope = unitService.getManagementUnitByName(s);
						List<ManagementUnitDict> units = unitService.getManagementUnitByParent(scope.getId());
						for (ManagementUnitDict managementUnitDict : units) {
							if(managementUnitDict.getUnitType().equals(ManagementUnitEnum.MAINTENANCE_MANAGEMENT)) {
								managements.add(managementUnitDict);
							}
						}
						scopeNameToUnits.put(modelOnFocus.getInspectionScope(), managements);
					}
				} catch (ManagementUnitException e) {
					e.printStackTrace();
				}
			}
			
		}
		if(StringUtils.isNotBlank(query)) {
			for(ManagementUnitDict unit : managements) {
				if(PingYinUtil.getPingYinHeader(unit.getName()).startsWith(query)) {
					result.add(unit.getName());
				}
			}
		}else {
			for(ManagementUnitDict unit : managements) {
				result.add(unit.getName());
			}
		}
		return result;
	}
	/**
	 * 
	 * @param model
	 */
	public List<String> completeInspectionExperts(String query) {
		List<String> result = new ArrayList<String>();
		if(StringUtils.isNotBlank(query)) {
			for(InspectionExpert expert : expertAll) {
				if(PingYinUtil.getPingYinHeader(expert.getName()).startsWith(query)) {
					if(!selectedExperts.contains(expert.getName())) {
						result.add(expert.getName());
					}
//						else {
//						result.add(expert.getName()+"(已选)");
//					}
				}
			}
		}else {
			for(InspectionExpert expert : expertAll) {
				if(!selectedExperts.contains(expert.getName())) {
					result.add(expert.getName());
				}
//				else {
//					result.add(expert.getName()+"(已选)");
////				}
			}
		}
		return result;
	}
	/**
	 * 
	 * @param model
	 */
	public void onInspectionExpertBlur(InspectOtherTreeTableDTO model) {
		if(StringUtils.isNotBlank(model.getInspectionExpert())) {
			for(InspectionExpert expert : expertAll) {
				if(expert.getName().equals(model.getInspectionExpert())) {
					model.setInspectionExpertId(expert.getCode());
					model.setInspectionExpertPhone(expert.getTelephone());
					if(StringUtils.isNotBlank(model.getOldInspectionExpert())) {
						if(selectedExperts.contains(model.getOldInspectionExpert())) {
							selectedExperts.remove(model.getOldInspectionExpert());
						}
					}
					selectedExperts.add(model.getInspectionExpert());
					model.setOldInspectionExpert(model.getInspectionExpert());
					return;
				}
			}
			addErrorMessage("您输入的【"+model.getInspectionExpert()+"】不是专家，请先将其设置为专家！");
			model.setInspectionExpert("");
			model.setInspectionExpertId("");
			model.setInspectionExpertPhone("");
			if(StringUtils.isNotBlank(model.getOldInspectionExpert())) {
				if(selectedExperts.contains(model.getOldInspectionExpert())) {
					selectedExperts.remove(model.getOldInspectionExpert());
				}
			}
			model.setOldInspectionExpert("");
		}else {
			if(StringUtils.isNotBlank(model.getOldInspectionExpert())) {
				if(selectedExperts.contains(model.getOldInspectionExpert())) {
					selectedExperts.remove(model.getOldInspectionExpert());
				}
			}
			model.setOldInspectionExpert("");
		}
	}
	/**
	 * 
	 * @param model
	 */
	public void onInspectionExpertSelect(InspectOtherTreeTableDTO model) {
		for(InspectionExpert expert : expertAll) {
			if(expert.getName().equals(model.getInspectionExpert())) {
				model.setInspectionExpertId(expert.getCode());
				model.setInspectionExpertPhone(expert.getTelephone());
				if(StringUtils.isNotBlank(model.getOldInspectionExpert())) {
					if(selectedExperts.contains(model.getOldInspectionExpert())) {
						selectedExperts.remove(model.getOldInspectionExpert());
					}
				}
				selectedExperts.add(model.getInspectionExpert());
				model.setOldInspectionExpert(model.getInspectionExpert());
				return;
			}
		}
	}
	/**
	 * 将model设置成选中
	 * @param model
	 */
	public void setModelSelected(InspectOtherTreeTableDTO model) {
		model.setSelected(true);
		selectedModels.add(model);
//		int index = inspectOtherModels.indexOf(model);
//		PrimeFaces.current().executeScript("setRowBgColor("+index+",'#999')");
	}
	/**
	 * 将model设置成为选中
	 * @param model
	 */
	public void setModelUnSelected(InspectOtherTreeTableDTO model) {
		model.setSelected(false);
		selectedModels.remove(model);
//		int index = inspectOtherModels.indexOf(model);
//		PrimeFaces.current().executeScript("setRowBgColor("+index+",'white')");
	}
	/**
	 * 获得当前操作的model
	 * @return
	 */
	private InspectOtherTreeTableDTO getModelOnFocus() {
		FacesContext context = FacesContext.getCurrentInstance();
		InspectOtherTreeTableDTO model = (InspectOtherTreeTableDTO) UIComponent.getCurrentComponent(context).getAttributes().get("model");
		return model;
	}
	/**
	 * 对targetModels进行排序
	 * 排序规则：1、先按专家派出分子公司 2、在按被检分子公司
	 * @param selectLists
	 */
	private void sortModelList(List<InspectOtherTreeTableDTO> selectLists) {
		selectLists.sort(Comparator.comparing(InspectOtherTreeTableDTO::getInspectionScope)
				.thenComparing(InspectOtherTreeTableDTO::getAcceptScope));
	}

	/**
	 * 组织机构人员选择器弹窗返回处理函数
	 */
	public void onUserDialogReturn() {
		String userJson = getParameter("userJson");
		String className = getParameter("className");
		if(PersonnelEntityBean.class.getSimpleName().equals(className) && StringUtils.isNoneBlank(userJson) ){
			PersonnelEntityBean user = JSONObject.parseObject(userJson, PersonnelEntityBean.class);
			targetPlan.setResponsible(user.getName());
			targetPlan.setResponsiblePhone(user.getTelephone());
    	}
	}
	/**
	 * 删除按钮是否可用
	 * @return
	 */
	public boolean disabledDelBtn() {
		if(selectedModels.isEmpty()) {
			return true;
		}
		return false;
	}
	/**
	 * 删除选中的节点，如果数据已保存则从数据库中删除
	 */
	public void deleteSelectedNodes() {
		Iterator<InspectOtherTreeTableDTO> it = selectedModels.iterator();
		while(it.hasNext()) {
			//1.删除
			InspectOtherTreeTableDTO model = it.next();
			if(model.isFormDB()) {
				try {
					stationService.deleteById(model.getInspectionStationId());
					it.remove();
					inspectOtherModels.remove(model);
				} catch (ParameterException e) {
					addErrorMessage("删除失败！");
				}
			}else {
				it.remove();
				inspectOtherModels.remove(model);
			}
			addSuccessMessage("删除成功！");
			//2.减去数量
			Integer num1 = inspectionScopeToAcceptUnitNum.get(model.getInspectionScope());
			num1--;
			inspectionScopeToAcceptUnitNum.replace(model.getInspectionScope(),num1);
			Integer num2 = acceptScopeToAcceptUnitNum.get(model.getInspectionScope()+"-"+model.getAcceptScope());
			num2--;
			acceptScopeToAcceptUnitNum.replace(model.getInspectionScope()+"-"+model.getAcceptScope(), num2);
			//3.更新组别
			if(StringUtils.isNotBlank(model.getInspectionExpertGroup())) {
				Map<Integer, Integer> groupInfo = inspectionScopeNameToGroup.get(model.getInspectionScope());
				Integer count = groupInfo.get(Integer.parseInt(model.getInspectionExpertGroup()));
				count--;
				groupInfo.replace(Integer.parseInt(model.getInspectionExpertGroup()), count);
			}
			
		}
	}

	/**
	 * 保存该互查计划
	 */
	public void saveAssessmentPlan() {
		if(saveIsAvailable()) {
			//1.保存计划
			if(StringUtils.isEmpty(planId)) {//新建计划时
				targetPlan.setCreateTime(new Date());
				targetPlan.setStatus(0);
			}
			InspectionPlan inspectionPlan = planService.createOrupdate(targetPlan);
			//2.保存评价厂站
			for(InspectOtherTreeTableDTO model : inspectOtherModels) {
				
				InspectionStation instation = convertFromInspectOtherTreeTableDTO(model);
				instation.setInspectPlan(inspectionPlan);
				stationService.update(instation);
			}
			
			//关闭弹窗并返回数据
			JSONObject r = new JSONObject();
			r.put("inspectionPlanId", inspectionPlan.getId());
			PrimeFaces.current().executeScript("closeAndSave("+r.toJSONString()+")");
		}
	}
	/**
	 * 将InspectOtherTreeTableDTO转成InspectionStation
	 * @param model
	 * @return
	 */
	private InspectionStation convertFromInspectOtherTreeTableDTO(InspectOtherTreeTableDTO model) {
		InspectionStation instation = new InspectionStation();
		instation.setId(model.getInspectionStationId());
		instation.setInspectionScope(model.getInspectionScope());
		instation.setInspectionUnit(model.getInspectionUnit());
		instation.setInspectionScopePersonnel(model.getInspectionScopePersonnel());
		instation.setInspectionScopePersonnelPhone(model.getInspectionScopePersonnelPhone());
		instation.setAcceptScope(model.getAcceptScope());
		instation.setAcceptUnit(model.getAcceptUnit());
		instation.setStationId(model.getStationId());
		instation.setStationName(model.getStationName());
		instation.setStationPersonnel(model.getStationPersonnel());
		instation.setStationPersonnelPhone(model.getStationPersonnelPhone());
		instation.setStartTime(model.getStartTime());
		instation.setEndTime(model.getEndTime());
		instation.setInspectionExpert(model.getInspectionExpert());
		instation.setInspectionExpertId(model.getInspectionExpertId());
		instation.setInspectionExpertPhone(model.getInspectionExpertPhone());
		if(StringUtils.isNotBlank(model.getInspectionExpertGroup())) {
			instation.setInspectionExpertGroup(Integer.parseInt(model.getInspectionExpertGroup()));
		}
		if(StringUtils.isNotBlank(model.getStationType())) {
			SubStationTypeEnum type = null;
			for(SubStationTypeEnum stationType : SubStationTypeEnum.values()) {
				if(stationType.name().equals(model.getStationType())) {
					type = stationType;
				}
			}
			instation.setStationType(type);
		}
		return instation;
	}
	/**
	 * 判断是否可用保存计划为草稿
	 * 可以保存的条件：
	 * 1.计划基本信息完整：评价名称、评价时间、负责人已填写
	 * @return
	 */
	private boolean saveIsAvailable() {
		if(StringUtils.isBlank(targetPlan.getName())) {
			alertErrorMessage("请填写该计划名称！");
			return false;
		}
//		if(targetPlan.getStartTime()==null||targetPlan.getEndTime()==null) {
//			alertErrorMessage("请完善评价计划时间！");
//			return false;
//		}
		if(StringUtils.isBlank(targetPlan.getResponsible())) {
			alertErrorMessage("请填写负责人！");
			return false;
		}
		if(StringUtils.isBlank(targetPlan.getResponsiblePhone())) {
			alertErrorMessage("请填写负责人联系方式！");
			return false;
		}
		return true;
	}
		
	/**
	 * 添加胡查项弹窗返回处理函数
	 */
	public void onSetInspectOtherItemDialogReturn() {
		String inspectionScopeData = getParameter("inspectionScope");
		List<InspectionScopeModel> models = handleInspectionScopeData(inspectionScopeData);
		StringBuffer buffer = new StringBuffer("");
		for(InspectionScopeModel model : models) {
			buffer.append(model.getInspectionScope()).append(",");
		}
		buffer.deleteCharAt(buffer.lastIndexOf(","));
		String inspectionScope = buffer.toString();
		String acceptUnits = getParameter("acceptUnits");
		Map<String,List<String>> scopeNameToUnits = handleAcceptUnits(acceptUnits,inspectionScope);
		for(String acceptScope : scopeNameToUnits.keySet()) {
			List<String> units = scopeNameToUnits.get(acceptScope);
			String key = inspectionScope+"-"+acceptScope;
			if(!acceptScopeToAcceptUnitNum.containsKey(key)) {
				acceptScopeToAcceptUnitNum.put(key, 0);
			}
			Integer num = acceptScopeToAcceptUnitNum.get(key);
			num+=units.size();
			acceptScopeToAcceptUnitNum.replace(key, num);
			int index = 0;
			int inspectionScopeNum = models.size();
			for(String acceptUnit : units) {
				InspectOtherTreeTableDTO dto = new InspectOtherTreeTableDTO();
				int indexOfModels = index%inspectionScopeNum;
				InspectionScopeModel model = models.get(indexOfModels);
				dto.setInspectionStationId(ObjectId.get().toString());
				dto.setInspectionScope(inspectionScope);
				dto.setAcceptScope(acceptScope);
				dto.setAcceptUnit(acceptUnit);
				if(StringUtils.isNotBlank(model.getInspectionScopePersonnel())) {
					dto.setInspectionScopePersonnel(model.getInspectionScopePersonnel());
				}
				if(StringUtils.isNotBlank(model.getInspectionScopePersonnelPhone())) {
					dto.setInspectionScopePersonnelPhone(model.getInspectionScopePersonnelPhone());
				}
				inspectOtherModels.add(dto);
				index++;
			}
		}
		//排序
		sortModelList(inspectOtherModels);
	}
	/**
	 * 
	 * @param inspectionScopeData:派出分子公司-派出联系人名称-派出联系人电话，------
	 * @return
	 */
	private List<InspectionScopeModel> handleInspectionScopeData(String inspectionScopeDatas) {
		List<InspectionScopeModel> models = new ArrayList<InspectionScopeModel>();
		if(inspectionScopeDatas.contains(",")) {
			String[] inspectionScopeItems = inspectionScopeDatas.split(",");
			for(int i=0;i<inspectionScopeItems.length;i++) {
				InspectionScopeModel model = new InspectionScopeModel();
				String[] inspectionScopeData = inspectionScopeItems[i].split("-");
				model.setInspectionScope(inspectionScopeData[0]);
				if(!"null".equals(inspectionScopeData[1])) {
					model.setInspectionScopePersonnel(inspectionScopeData[1]);
				}
				if(!"null".equals(inspectionScopeData[2])) {
					model.setInspectionScopePersonnelPhone(inspectionScopeData[2]);
				}
				models.add(model);
			}
		}else {
			InspectionScopeModel model = new InspectionScopeModel();
			String[] inspectionScopeData = inspectionScopeDatas.split("-");
			model.setInspectionScope(inspectionScopeData[0]);
			if(!"null".equals(inspectionScopeData[1])) {
				model.setInspectionScopePersonnel(inspectionScopeData[1]);
			}
			if(!"null".equals(inspectionScopeData[2])) {
				model.setInspectionScopePersonnelPhone(inspectionScopeData[2]);
			}
			models.add(model);
		}
		return models;
	}
	/**
	 * 
	 * @param acceptunits 被检单位id使用“，”拼接的字符串
	 * @param inspectionScope 
	 * @return key: 被检单位分子公司name  value:被检单位name
	 */
	private Map<String,List<String>> handleAcceptUnits(String acceptunits, String inspectionScope) {
		Map<String,List<String>> scopeNameToUnits = new HashMap<String, List<String>>();
		String[] acceptUnitArray = acceptunits.split(",");
		List<String> acceptUnitList = Arrays.asList(acceptUnitArray);
		if(!inspectionScopeToAcceptUnitNum.containsKey(inspectionScope)) {
			inspectionScopeToAcceptUnitNum.put(inspectionScope, 0);
		}
		Integer num = inspectionScopeToAcceptUnitNum.get(inspectionScope);
		num+=acceptUnitList.size();
		inspectionScopeToAcceptUnitNum.replace(inspectionScope, num);
		try {
			for(String acceptUnitId : acceptUnitList) {
				ManagementUnitDict unit = unitService.getManagementUnit(acceptUnitId);
				ManagementUnitDict scope = unitService.getManagementUnit(unit.getPid());
				if(scopeNameToUnits.containsKey(scope.getName())) {
					scopeNameToUnits.get(scope.getName()).add(unit.getName());
				}else {
					List<String> unitNames = new ArrayList<String>();
					unitNames.add(unit.getName());
					scopeNameToUnits.put(scope.getName(), unitNames);
				}
			}
		} catch (ManagementUnitException e) {
			e.printStackTrace();
		}
		return scopeNameToUnits;
	}
	/**
	 * 新增专家后调用函数
	 */
	public void setExpert() {
		expertAll = expertService.findAll();
	}
	public InspectionPlan getTargetPlan() {
		return targetPlan;
	}
	public void setTargetPlan(InspectionPlan targetPlan) {
		this.targetPlan = targetPlan;
	}
	public List<InspectOtherTreeTableDTO> getInspectOtherModels() {
		return inspectOtherModels;
	}
	public void setInspectOtherModels(List<InspectOtherTreeTableDTO> inspectOtherModels) {
		this.inspectOtherModels = inspectOtherModels;
	}
	public List<InspectOtherTreeTableDTO> getSelectedModels() {
		return selectedModels;
	}
	public void setSelectedModels(List<InspectOtherTreeTableDTO> selectedModels) {
		this.selectedModels = selectedModels;
	}
	
}
